package cn.com.server.controller.orderListManager;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;

import cn.com.server.common.AjaxCodeUtil;
import cn.com.server.common.AjaxObject;
import cn.com.server.common.util.DateUtil;
import cn.com.server.common.util.RedisUtils;
import cn.com.server.entity.ProductDetail;
import cn.com.server.entity.ProductMain;
import cn.com.server.service.ProductListService;
import cn.com.server.shiro.entity.User;
import cn.com.server.extend.model.ProductListModel;
import cn.com.server.extend.view.ProductListView;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author qing
 * @since 2017-11-15
 */
@Controller
@RequestMapping("/productList")
public class ProductListController {

    @Autowired
    private RedisUtils redisUtils;
    
	@Autowired
	private ProductListService productListService;

	@RequestMapping("/productListView")
	public String orderListView(HttpServletRequest request, HttpServletResponse response) {
        redisUtils.set("123", "hello world");
        System.out.println("进入了方法");
        String string= redisUtils.get("123").toString();
        System.out.println("string:"+string);
		return "/productListManager/productListView";
	}

	@RequestMapping("/getProductList")
	@ResponseBody
	public AjaxObject getProductList(ProductListModel productListModel, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		Page<ProductListView> pageData = productListService.selectProductListModel(productListModel);
		AjaxObject ajaxObject = AjaxCodeUtil.getAjaxObject("success");
		ajaxObject.setData(pageData);
		return ajaxObject;
	}

	@RequestMapping("/save")
	@ResponseBody
	public AjaxObject saveProductList(ProductListModel productListModel, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		try {
			ProductMain productMain = new ProductMain();
			Subject subject = SecurityUtils.getSubject();
			User user = (User) subject.getPrincipal();
			productMain.setSku(productListModel.getSku());
			productMain.setCreateMan(user.getId());
			new DateUtil();
			productMain.setCreateTime(DateUtil.getCurrentDateTime());
			productMain.setBarcode(productListModel.getBarcode());
			productMain.setNameCn(productListModel.getNameCn());
			productMain.setCategory(productListModel.getCategory());
			productMain.setRemarker(productListModel.getRemarker());
			List<String> stockIds = productListModel.getStockIds();
			stockIds.remove(null);
			List<ProductDetail> productDeatilList = new ArrayList<ProductDetail>();
			for (String stock : stockIds) {
				ProductDetail productDetail = new ProductDetail();
				productDetail.setCurrentNum(11.0);
				productDetail.setProductMainId(productMain.getId());
				productDetail.setCurrentPrice(productListModel.getCurrentPrice());
				productDetail.setStockId(Integer.valueOf(stock));
				productDeatilList.add(productDetail);
			}
			productListService.createProduct(productMain, productDeatilList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return AjaxCodeUtil.getAjaxObject("success");
	}

	@RequestMapping("/upload")
	@ResponseBody
	public AjaxObject batchimport(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response,HttpSession session) throws IOException {
		// 判断文件是否为空
		if (file == null)
			return null;
		// 获取文件名
		String name = file.getOriginalFilename();
		// 进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
		long size = file.getSize();
		if (name == null || ("").equals(name) && size == 0)
			return null;
		String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
		if (type == ".xls" || type == ".xlsx")
			return null;
		String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
		String path = request.getSession(true).getServletContext().getRealPath("/upload/" + filename);
		System.out.println(path);
		File destFile = new File(path);
		// FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作，不需要额外的再去关闭IO流
		FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
		readExecl(path);
		return AjaxCodeUtil.getAjaxObject("success");
	}

	// poi 读取 execel内容
	public boolean readExecl(String path) throws FileNotFoundException, IOException {
		XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
		XSSFSheet sheet = null;
		for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 获取每个Sheet表
			sheet = workbook.getSheetAt(i);
			for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {// getLastRowNum，获取最后一行的行标
				XSSFRow row = sheet.getRow(j);
				if (row != null) {
					for (int k = 0; k < row.getLastCellNum(); k++) {// getLastCellNum，是获取最后一个不为空的列是第几个
						if (row.getCell(k) != null) { // getCell 获取单元格数据
							System.out.print(row.getCell(k) + "\t");
						} else {
							System.out.print("\t");
						}
					}
				}
				System.out.println(""); // 读完一行后换行
			}
			System.out.println("读取sheet表：" + workbook.getSheetName(i) + " 完成");
		}
		return true;
	}

	/**
	 * 文件下载
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/downloadData")
	public String downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		File file = new File("C:/Users/Administrator/Desktop/测试.xlsx");
		FileOutputStream outputStream = new FileOutputStream(file);
		Workbook wb = new XSSFWorkbook();
		Sheet sheet = wb.createSheet("sheet1");
		Row row = null;
		row = sheet.createRow(0);
		Cell cell = null;
		cell = row.createCell(0);
		cell.setCellValue("商品名称");
		cell = row.createCell(1);
		cell.setCellValue("sku");
		cell = row.createCell(2);
		cell.setCellValue("价格");

		row = sheet.createRow(1);
		cell = row.createCell(0);
		cell.setCellValue("测试");
		cell = row.createCell(1);
		cell.setCellValue("ssdfe");
		cell = row.createCell(2);
		cell.setCellValue("32.0");

		wb.write(outputStream);
		outputStream.flush();
		outputStream.close();

		if (file.exists()) {
			response.setContentType("application/force-download");
			response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream os = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					os.write(buffer, 0, i);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}
}
